package com.orderplus.opshop.common.util;

import com.orderplus.opshop.core.constants.MessageConstant;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

/**
 * Created by zhouxj6112 on 2018/12/1.
 */
public class PropertiesUtil {

	private static ResourceBundle dataResourceBundle;

	private PropertiesUtil() {

	}

	static {
		try {
			dataResourceBundle = new PropertyResourceBundle(new BufferedInputStream(new FileInputStream(new File(Thread.currentThread()
					.getContextClassLoader().getResource("datasource.properties").getPath()))));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String getDataSourceConfig(String key) {
		String value = "";
		try {
			// 先从环境变量取，环境变量没值的时候，再从配置文件取
			if (System.getenv().containsKey(key)) {
				value = System.getenv(key);
			} else {
				value = new String(dataResourceBundle.getString(key).getBytes("ISO-8859-1"), "UTF8");
			}
		} catch (Exception e) {
			throw new IllegalArgumentException(MessageConstant.ENV_OR_CONFIG_NOT_FOUND);
		}
		return value;
	}

	public static String getStringConfig(String key, ResourceBundle data) {
		String value;
		if (System.getenv().containsKey(key)) {
			value = System.getenv(key);
		} else {
			value = data.getString(key);
		}
		return value;
	}

	public static String getStringConfig(String key) {
		String value;
		if (System.getenv().containsKey(key)) {
			value = System.getenv(key);
		} else {
			value = dataResourceBundle.getString(key);
		}
		return value;
	}

	public static int getIntConfig(String key, ResourceBundle data) {
		int value;
		try {
			String s;
			if (System.getenv().containsKey(key)) {
				s = System.getenv(key);
			} else {
				s = data.getString(key);
			}
			value = Integer.parseInt(s);
		} catch (Exception e) {
			throw new NumberFormatException();
		}
		return value;
	}

	public static Boolean getBooleanConfig(String key, ResourceBundle data) {
		Boolean value;
		try {
			String s;
			if (System.getenv().containsKey(key)) {
				s = System.getenv(key);
			} else {
				s = data.getString(key);
			}
			value = Boolean.parseBoolean(s);
		} catch (Exception e) {
			throw new NumberFormatException();
		}
		return value;
	}

	public static Boolean getBooleanConfig(String key) {
		String value;
		if (System.getenv().containsKey(key)) {
			value = System.getenv(key);
		} else {
			value = dataResourceBundle.getString(key);
		}
		return Boolean.parseBoolean(value);
	}

}
